<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { useMerchantStore } from "@/store";
import { ElMessage } from "element-plus";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";
import StarRating from "@/components/common/StarRating.vue";

const merchantStore = useMerchantStore();
const reviews = ref<any[]>([]);
const stats = ref<{ average: number; total: number }>({ average: 0, total: 0 });
const loading = ref(false);

// 筛选条件
const filters = reactive({
  score: null as number | null,
  dateRange: null as [Date, Date] | null,
  keyword: "",
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取评价列表和统计
const fetchReviews = async () => {
  if (!merchantStore.currentStoreId) {
    reviews.value = [];
    stats.value = { average: 0, total: 0 };
    return;
  }

  loading.value = true;
  try {
    const { listReviews } = await import("@/api/index");

    // 构建查询参数
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value,
    };

    // 添加筛选条件
    if (filters.score) {
      params.score = filters.score;
    }

    if (
      filters.dateRange &&
      Array.isArray(filters.dateRange) &&
      filters.dateRange.length === 2
    ) {
      params.startDate = filters.dateRange[0];
      params.endDate = filters.dateRange[1];
    }

    if (filters.keyword) {
      params.keyword = filters.keyword;
    }

    // 评价列表
    const reviewRes = await listReviews(merchantStore.currentStoreId, params);

    // 处理返回数据
    const data = reviewRes.data?.data || reviewRes.data;
    if (data) {
      reviews.value = data.content;
      total.value = data.content.length;
    } else {
      reviews.value = [];
      total.value = 0;
    }

    // 评价统计：从评价列表中计算平均分和总数
    if (reviews.value.length > 0) {
      const totalScore = reviews.value.reduce(
        (sum, review) => sum + review.storeRating || 0,
        0
      );
      stats.value.average = totalScore / reviews.value.length;
      stats.value.total = reviews.value.length;
    } else {
      stats.value.average = 0;
      stats.value.total = 0;
    }
  } catch (error) {
    console.error("获取评价数据失败", error);
    ElMessage.error("获取评价数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchReviews();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchReviews();
};

// 重置筛选条件
const resetFilters = () => {
  filters.score = null;
  filters.dateRange = null;
  filters.keyword = "";
  currentPage.value = 1;
  fetchReviews();
};

// 应用筛选条件
const applyFilters = () => {
  currentPage.value = 1;
  fetchReviews();
};

onMounted(async () => {
  // 确保店铺信息已加载
  if (merchantStore.stores.length === 0) {
    await merchantStore.fetchStores();
  }

  // 获取评价列表和统计
  await fetchReviews();
});

// 监听店铺变化
watch(
  () => merchantStore.currentStoreId,
  () => {
    currentPage.value = 1;
    fetchReviews();
  }
);
</script>

<template>
  <merchant-layout>
    <div class="reviews-view">
      <el-card class="reviews-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>评价管理</span>
          </div>
        </template>

        <div v-if="!merchantStore.currentStoreId" class="no-store-tip">
          <el-empty description="请先选择店铺" />
        </div>

        <template v-else>
          <!-- 评价统计 -->
          <div class="review-stats">
            <div class="stats-item">
              <div class="stats-label">平均评分</div>
              <div class="stats-value">
                <star-rating :score="stats.average" :precision="1" />
              </div>
            </div>
            <div class="stats-item">
              <div class="stats-label">总评价数</div>
              <div class="stats-value">{{ stats.total }}</div>
            </div>
          </div>

          <!-- 筛选条件 -->
          <div class="filter-container">
            <el-form :inline="true" class="filter-form">
              <el-form-item label="评分">
                <el-select v-model="filters.score" placeholder="全部" clearable>
                  <el-option label="5星" :value="5" />
                  <el-option label="4星" :value="4" />
                  <el-option label="3星" :value="3" />
                  <el-option label="2星" :value="2" />
                  <el-option label="1星" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="filters.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item label="关键词">
                <el-input
                  v-model="filters.keyword"
                  placeholder="搜索评价内容"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="applyFilters">筛选</el-button>
                <el-button @click="resetFilters">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 评价列表 -->
          <el-table
            :data="reviews"
            v-loading="loading"
            style="width: 100%"
            stripe
          >
            <el-table-column prop="userName" label="用户" />
            <el-table-column prop="score" label="评分" width="180">
              <template #default="scope">
                <star-rating :score="scope.row.storeRating" :precision="1" />
              </template>
            </el-table-column>
            <el-table-column
              prop="content"
              label="内容"
              show-overflow-tooltip
            />
            <el-table-column prop="createdAt" label="时间" width="180" />
            <el-table-column label="操作" width="180">
              <template #default>
                <el-button
                  size="small"
                  type="primary"
                  @click="($event) => ElMessage.info('查看评价详情')"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </template>
      </el-card>
    </div>
  </merchant-layout>
</template>

<style scoped>
.reviews-view {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.store-selector {
  display: flex;
  align-items: center;
}

.store-selector .label {
  margin-right: 10px;
  color: #909399;
}

.el-main {
  padding: 20px;
}

.reviews-card {
  border-radius: 18px;
  background: #fffbe7;
  box-shadow: 0 2px 8px #ffd54f33;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-store-tip {
  padding: 30px 0;
}

.review-stats {
  display: flex;
  margin-bottom: 24px;
  background-color: #fff8e1;
  padding: 16px;
  border-radius: 8px;
}

.stats-item {
  margin-right: 40px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 18px;
  color: #d2691e;
  font-weight: 500;
}

.filter-container {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.reply-form {
  padding: 10px 0;
}

.reply-actions {
  margin-top: 10px;
  text-align: right;
}
</style>
